import { View, Text, StyleSheet, TextInput, TouchableOpacity, KeyboardAvoidingView, Platform, ScrollView, Image, ActivityIndicator } from 'react-native';
import { useState, useEffect } from 'react';
import { useRouter, useNavigation } from 'expo-router';
import { userService, fileService } from '../../utils/api/services';
import { API_BASE_URL } from '../../utils/api/config';
import { MaterialIcons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import Toast from 'react-native-toast-message';
import { useAuth } from '../../store/auth/AuthContext';

export default function EditProfileScreen() {
  const router = useRouter();
  const navigation = useNavigation();
  const { user } = useAuth();
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [userInfo, setUserInfo] = useState({
    nickname: '',
    bio: '',
    avatar: '',
  });
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  // 检查用户登录状态
  useEffect(() => {
    if (!user?.id) {
      Toast.show({
        type: 'error',
        text1: '请先登录',
        text2: '登录后才能编辑个人资料',
      });
      router.replace('/user/login');
      return;
    }
  }, [user, router]);

  // 获取用户信息
  useEffect(() => {
    const fetchUserInfo = async () => {
      if (!user?.id) return;

      try {
        const response = await userService.getUser(Number(user.id));
        console.log('获取到的用户信息:', response?.data);
        
        if (response?.data) {
          setUserInfo({
            nickname: response.data.nickname || '',
            bio: response.data.bio || '',
            avatar: response.data.avatar || '',
          });
          if (response.data.avatar) {
            setSelectedImage(response.data.avatar);
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        Toast.show({
          type: 'error',
          text1: '获取用户信息失败',
          text2: '请稍后重试',
        });
      } finally {
        setLoading(false);
      }
    };

    fetchUserInfo();
  }, [user?.id]);

  // 选择图片
  const handleSelectImage = async () => {
    if (!user?.id) {
      Toast.show({
        type: 'error',
        text1: '用户未登录',
        text2: '请先登录后再操作',
      });
      router.replace('/user/login');
      return;
    }

    try {
      // 请求权限
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        Toast.show({
          type: 'error',
          text1: '需要访问相册权限',
          text2: '请在设置中允许访问相册',
        });
        return;
      }

      // 选择图片
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [1, 1],
        quality: 0.8,
      });

      if (!result.canceled && result.assets[0].uri) {
        // 创建FormData对象
        const formData = new FormData();
        const fileType = result.assets[0].uri.split('.').pop() || 'jpg';
        const timestamp = Date.now();
        
        formData.append('file', {
          uri: result.assets[0].uri,
          type: `image/${fileType}`,
          name: `avatar_${timestamp}.${fileType}`,
        } as any);

        try {
          // 上传文件
          const response = await fileService.uploadFile(formData);
          console.log('文件上传响应:', response);
          
          if (response?.data?.url) {
            // 拼接完整的URL并添加时间戳参数
            const fullUrl = response.data.url.startsWith('http') 
              ? `${response.data.url}?t=${timestamp}`
              : `${API_BASE_URL}${response.data.url}?t=${timestamp}`;
            
            // 更新预览图和用户信息中的头像URL
            setSelectedImage(fullUrl);
            setUserInfo(prev => ({ ...prev, avatar: response.data.url }));
            Toast.show({
              type: 'success',
              text1: '头像上传成功',
            });
          } else {
            throw new Error('未获取到文件URL');
          }
        } catch (error) {
          console.error('上传头像失败:', error);
          Toast.show({
            type: 'error',
            text1: '上传头像失败',
            text2: '请稍后重试',
          });
        }
      }
    } catch (error) {
      console.error('选择图片失败:', error);
      Toast.show({
        type: 'error',
        text1: '选择图片失败',
        text2: '请稍后重试',
      });
    }
  };

  const handleSubmit = async () => {
    if (!user?.id) {
      Toast.show({
        type: 'error',
        text1: '用户未登录',
        text2: '请先登录后再操作',
      });
      router.replace('/user/login');
      return;
    }

    if (!userInfo.nickname.trim()) {
      Toast.show({
        type: 'error',
        text1: '请输入昵称',
      });
      return;
    }

    try {
      setSubmitting(true);
      await userService.updateUser(Number(user.id), {
        nickname: userInfo.nickname,
        bio: userInfo.bio,
        avatar: userInfo.avatar,
      });
      
      Toast.show({
        type: 'success',
        text1: '保存成功',
      });

      // 更新前一个页面的数据
      if (navigation.canGoBack()) {
        // @ts-ignore
        navigation.getParent()?.setParams({ refresh: Date.now() });
      }
      
      router.back();
    } catch (error) {
      console.error('更新用户信息失败:', error);
      Toast.show({
        type: 'error',
        text1: '保存失败',
        text2: '请稍后重试',
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#007AFF" />
      </View>
    );
  }

  return (
    <KeyboardAvoidingView 
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <MaterialIcons name="arrow-back" size={24} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>编辑资料</Text>
        <View style={styles.headerRight} />
      </View>

      <ScrollView style={styles.content}>
        <TouchableOpacity style={styles.avatarContainer} onPress={handleSelectImage}>
          {selectedImage ? (
            <Image 
              source={{ 
                uri: selectedImage.includes('?') 
                  ? selectedImage 
                  : selectedImage.startsWith('http')
                    ? `${selectedImage}?t=${Date.now()}`
                    : `${API_BASE_URL}${selectedImage}?t=${Date.now()}`
              }} 
              style={styles.avatar} 
            />
          ) : (
            <View style={styles.avatarPlaceholder}>
              <MaterialIcons name="add-photo-alternate" size={40} color="#666" />
              <Text style={styles.avatarPlaceholderText}>点击上传头像</Text>
            </View>
          )}
        </TouchableOpacity>

        <View style={styles.inputGroup}>
          <Text style={styles.label}>昵称</Text>
          <TextInput
            style={styles.input}
            value={userInfo.nickname}
            onChangeText={(text) => setUserInfo(prev => ({ ...prev, nickname: text }))}
            placeholder="请输入昵称"
            placeholderTextColor="#999"
          />
        </View>

        <View style={styles.inputGroup}>
          <Text style={styles.label}>个人简介</Text>
          <TextInput
            style={[styles.input, styles.bioInput]}
            value={userInfo.bio}
            onChangeText={(text) => setUserInfo(prev => ({ ...prev, bio: text }))}
            placeholder="介绍一下自己吧"
            placeholderTextColor="#999"
            multiline
            numberOfLines={4}
            textAlignVertical="top"
          />
        </View>
      </ScrollView>

      <View style={styles.footer}>
        <TouchableOpacity
          style={[styles.submitButton, submitting && styles.submitButtonDisabled]}
          onPress={handleSubmit}
          disabled={submitting}
        >
          <Text style={styles.submitButtonText}>
            {submitting ? '保存中...' : '保存修改'}
          </Text>
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  headerRight: {
    width: 32,
  },
  content: {
    flex: 1,
    padding: 16,
  },
  avatarContainer: {
    alignItems: 'center',
    marginBottom: 24,
  },
  avatar: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: '#f5f5f5',
  },
  avatarPlaceholder: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#ddd',
    borderStyle: 'dashed',
  },
  avatarPlaceholderText: {
    fontSize: 12,
    color: '#666',
    marginTop: 8,
    textAlign: 'center',
  },
  inputGroup: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    color: '#333',
    marginBottom: 8,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: '#333',
  },
  bioInput: {
    height: 120,
    textAlignVertical: 'top',
  },
  footer: {
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  submitButton: {
    backgroundColor: '#007AFF',
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  submitButtonDisabled: {
    backgroundColor: '#ccc',
  },
  submitButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
}); 